package com.tuanzi.loan.security;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.tuanzi.loan.business.service.system.SystemUserService;
import com.tuanzi.loan.core.util.IPUtils;
import com.tuanzi.loan.log.entity.LoginLogAction;
import com.tuanzi.loan.log.service.LoginLogService;

@Component
public class LoanAuthenticationFailureHandler implements AuthenticationFailureHandler {

	@Autowired
	private SystemUserService userService;
	@Autowired
	private LoginLogService loginLogService;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

		String username = request.getParameter("username");
		AuthenticationFailureType failureType = null;

		if (exception instanceof DisabledException) {
			failureType = AuthenticationFailureType.DISABLED;
		} else if (exception instanceof BadCredentialsException) {
			failureType = AuthenticationFailureType.BAD_CREDENTIAL;
			userService.increseRetryTimes(username);
		} else if (exception instanceof LockedException) {
			failureType = AuthenticationFailureType.LOCKED;
		} else if (exception instanceof InternalAuthenticationServiceException) {
			failureType = AuthenticationFailureType.NO_USER;
		} else {
			failureType = AuthenticationFailureType.ERROR;
		}

		loginLogService.log(LoginLogAction.LOGIN_FAILURE, username, IPUtils.getIpAddress(request), failureType.getMessage());

		String contextPath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();

		response.sendRedirect(contextPath + "/login.xhtml?failureType=" + failureType.name());
	}
}
